import '../dao/ImSensitiveWordDao.dart';
import '../pojo/ImPojo.dart';
import '../socket/dto/business/PullData2.dart';
import 'BaseService.dart';

class ImSensitiveWordService extends BaseService {

  Future<void> saveOrUpdates(String userId, List<SensitiveWordItem> sensitiveWordItemList) async {
    if (sensitiveWordItemList.isEmpty) return;

    var sensitiveWordDao = new ImSensitiveWordDao();

    var imSensitiveWordList = sensitiveWordItemList.map((sw)=>_toImSensitiveWord(sw)).toList();

    List<String> wordList = sensitiveWordItemList.map((sw)=>sw.word).toList();
    var dbWords = await sensitiveWordDao.getByWords(wordList);
    Map<String, ImSensitiveWord> dbWordMap = Map.fromIterable(dbWords, key: (sensitiveWord)=>sensitiveWord.wrord,
        value: (sensitiveWord)=>sensitiveWord);

    var insertSensitiveWordList = <ImSensitiveWord>[];
    var updateSensitiveWordList = <ImSensitiveWord>[];
    for (var sensitiveWord in imSensitiveWordList) {
      var dbSensitiveWord = dbWordMap[sensitiveWord.word];
      if (dbSensitiveWord == null) {
        insertSensitiveWordList.add(sensitiveWord);
      } else {
        sensitiveWord.id = dbSensitiveWord.id;
        updateSensitiveWordList.add(sensitiveWord);
      }
    }

    sensitiveWordDao.batchInserts(insertSensitiveWordList);
    sensitiveWordDao.batchUpdates(updateSensitiveWordList);

  }

  ImSensitiveWord _toImSensitiveWord(SensitiveWordItem sensitiveWordItem) {
    var imSensitiveWord = ImSensitiveWord(word: sensitiveWordItem.word);
    imSensitiveWord.status = ImSensitiveWordStatus.ofValue(sensitiveWordItem.status.value);
    return imSensitiveWord;
  }
}